//
//  JLUserAccount.swift
//  新浪微博
//
//  Created by linlin on 15/11/25.
//  Copyright © 2015年 jilin. All rights reserved.
//

import UIKit

class JLUserAccount: NSObject , NSCoding{

    
    //用户是否登录
    class var userLogin: Bool {
        return JLUserAccount.loadAccount() != nil
    }
    
    
    var access_token: String?
    
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    //过期时间的NSDate形式
    var expiresDate: NSDate?
    
    var uid: String?
    
    
    //用户昵称
    var screen_name: String?
    
    //用户头像
    var avatar_large: String?
    
    
    
    //字典转模型方法 -重写构造方法
    init(dict: [String : AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    
    ///当kvc字典的key在模型中找不到对应的属性的时候调用:调用后找不到key就不会报错了
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        print("\(key)")
    }
    
    
    
    //重写discription属性
    override var description: String {
        
        return "access_token: \(access_token), expires_in: \(expires_in), expiresDate: \(expiresDate), uid: \(uid)"
    }
    
    
    
    ///存储--保存在沙盒
    //保存的路径  static-对象方法可以访问这个属性
    static let plistPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/account.plist"
    
    
    //保存数据的方法
    func saveAccount() {
        //归档
        NSKeyedArchiver.archiveRootObject(self, toFile: JLUserAccount.plistPath)
    }
    
    ///内存中的用户信息 - 类方法要调用，加static
    private static var userAccount: JLUserAccount?

    //加载用户数据方法
    class func loadAccount() ->JLUserAccount? {
        //判断内存中有没有数据
        if userAccount == nil {
            //到沙盒加载
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(plistPath) as? JLUserAccount
            print("从沙盒中加载数据")
        }else{
            print("从内存中加载数据")
        }
        
        //判断是否过期
        if userAccount != nil && userAccount?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            //有数据而且没有过期
            return userAccount
            
        }
        return nil
        
    }
    
    
    
    ///解档
    required init(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    
    ///归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        
        
    }
    
    
    
    
    //加载用户信息
    func loadUserInfo() {
        JLNetworkTool.sharedNetworkTool.loadAccountInfo { (result, error) -> () in
            
            if error != nil && result == nil {
                print("加载数据失败\(error)")
                return
            }
            
            //数据加载成功，保存数据
            self.screen_name = result!["screen_name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            
            
            //跟新userAccount属性
            JLUserAccount.userAccount = self
            
            //保存到沙盒中
            self.saveAccount()
        }

    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
